<template>
    <div class="command">
    <el-button type="primary" icon="el-icon-plus" style="margin-bottom:10px;" @click="showAdduser">添加用户</el-button>
    <el-table :data="tableData" style="width: 100%">
        <el-table-column prop="No" label="#" width="85" align="center">
        </el-table-column>
        <el-table-column label="id" v-if="hide" prop="id"></el-table-column>
        <el-table-column label="用户名"  prop="username" width="95"> 
            <template slot-scope="scope">
                <el-popover trigger="hover" placement="right-start">
                <p>ID:   {{ scope.row.id }}</p>
                <p>用户名:   {{ scope.row.username }}</p>
                <p>用户类型: {{ scope.row.type }}</p>
                <p>名称: {{ scope.row.name }}</p>
                <p>更新时间: {{ scope.row.updated_at }}</p>
                <p>注册时间: {{ scope.row.created_at }}</p>

                <div slot="reference" class="name-wrapper">
                    <el-tag size="medium">{{ scope.row.username }}</el-tag>
                </div>
                </el-popover>
            </template>
        </el-table-column>
        <el-table-column label="用户类型"  prop="type"> </el-table-column>
        <el-table-column label="注册时间"  prop="created_at"> </el-table-column>
        <el-table-column label="name"  prop="name" v-if="hide"> </el-table-column>
        <el-table-column label="更新时间"  prop="updated_at" v-if="hide"></el-table-column>
        
        <el-table-column align="right" width="340px;">
            <template slot-scope="scope">
                <el-button size="mini" icon="el-icon-edit-outline"
                @click="handleEdit(scope.row)">编辑</el-button>
                <el-button  size="mini" type="danger" icon="el-icon-circle-plus-outline"
                @click="handleAddAction(scope.row)">添加动作</el-button>
               
            </template>
        </el-table-column>
    </el-table>
      <el-pagination layout="prev, pager, next" :page-size="5" :total="total" @current-change="handleCurrentChange">
  </el-pagination>
    <!-- 用户编辑form -->
    <el-dialog title="修改" :visible.sync="editFormVisibe" width="30%">
         <el-form :model="editForm" ref="editForm" label-width="80px">
            <el-form-item prop="password" label="密码">
              <el-input v-model="editForm.password"  placeholder="请输入密码"></el-input>
            </el-form-item>
            <el-form-item prop="name" label="名称">
                <el-input v-model="editForm.name"  placeholder="请输入名称"></el-input>
            </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
            <el-button @click="resetForm('editForm')">重 置</el-button>
            <el-button type="primary" @click="editSubmitForm('editForm')">确 定</el-button>
        </div>
    </el-dialog>
     <!-- 新增动作指令form -->
    <el-dialog title="增加动作指令" :visible.sync="addFormVisibe" width="30%">
         <el-form :model="addForm"  ref="addForm" label-width="80px">
             <el-form-item prop="action" label="动作码" :rules="[{required: true, message: '请完善信息'}]">
              <el-input v-model="addForm.action"  placeholder="请输入动作码"></el-input>
          </el-form-item>
          <el-form-item prop="name" label="动作指令" :rules="[{required: true, message: '请完善信息'}]">
              <el-input v-model="addForm.name"  placeholder="请输入动作指令"></el-input>
          </el-form-item>
          <el-form-item prop="type" label="动作类型" :rules="[{required: true, message: '请选择'}]">
              <el-select v-model="addForm.type" placeholder="请选择">
                <el-option
                    v-for="item in actionOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value">
                    </el-option>
            </el-select>
          </el-form-item>
          <div>
              <el-form-item prop="content" label="描述" :rules="[{
                  required: true, message: '描述不能为空'
              }]">
                  <el-input v-model="addForm.content" type="textarea" ></el-input>
              </el-form-item>
          </div>
      </el-form>
        <div slot="footer" class="dialog-footer">
            <el-button @click="resetForm('addForm')">重 置</el-button>
            <el-button type="primary" @click="addSubmitForm('addForm')">确 定</el-button>
        </div>
    </el-dialog>
    <!-- 添加用户form -->
    <el-dialog title="新增用户" :visible.sync="addUserVisible" width="30%">
        <el-form :model="addUserForm" :rules="addUserRole" ref="addUserForm" label-width="60px" class="demo-ruleForm">
            <el-form-item label="用户名" prop="username">
                <el-input type="username" v-model="addUserForm.username"></el-input>
            </el-form-item>
            <el-form-item label="密码" prop="password">
                <el-input type="password" v-model="addUserForm.password"></el-input>
            </el-form-item>
            <el-form-item label="类型" prop="type">
            <el-select v-model="addUserForm.type" placeholder="请选择">
                <el-option
                    v-for="item in options"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value">
                    </el-option>
            </el-select>
            </el-form-item>
            <el-form-item label="名称" prop="name">
                <el-input v-model="addUserForm.name"></el-input>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="addUserSubmit('addUserForm')">提交</el-button>
                <el-button @click="resetForm('addUserForm')">重置</el-button>
            </el-form-item>
        </el-form>
    </el-dialog>
    </div>
</template>

<script>
export default {
    name:'command',
    data() {
      return {
        tableData: [],
        hide:false,
        total:0,
        pagenumber:1,
        addFormVisibe:false,
        editFormVisibe:false,
        detailFormVisible:false,
        addUserVisible:false,
        addForm:{
            user_id:'',
            name:'',
            action:'',
            content:'',
            type:'',
        },
        editForm:{
            password:'',
            name:''
        },
        addUserForm:{
            username:'',
            password:'',
            type:'',
            name:''
        },
        actionOptions:[{
            value:'0',
            label:'说话'
        },{
            value:'1',
            label:'切换界面'
        }],
        options:[{
            value:'0',
            label:'管理员'
        },{
            value:'1',
            label:'企业账户'
        }],
        
        addUserRole:{
          username: [
            { validator:this.checkStrig, trigger: 'blur' }
          ],
          password: [
            { validator:this.checkStrig, trigger: 'blur' }
          ],
          name:[
            { validator: this.checkName, trigger: 'blur' }
          ],
        },
        formLabelWidth:'80px'
      }
    },
    created: function() {
        this.getTableData();
    },
    methods: {
      // 自定义验证方法
      checkStrig(rule,value,callback){
          if(!value){
              callback(new Error('请完善信息'));
          }
          callback();
      },
      checkName(rule,value,callback){
          if(!this.addUserForm.type){
              callback(new Error('请选择用户类型'))
          }
          if(!value){
              callback(new Error('请输入名称'))
          }
          callback();
      },
      // 新增用户信息
      addUserSubmit(formName){
        this.$refs[formName].validate((valid) => {
            if(valid){
                var _this = this;
                POST(
                    urlApi+'auth/register',
                    {
                        username:_this.addUserForm.username,
                        password:_this.addUserForm.password,
                        type:_this.addUserForm.type,
                        name:_this.addUserForm.name
                    },
                    function(json){
                            if(json.code == 200){
                                _this.$message.success('添加成功');
                                _this.addUserVisible = false;
                            } else {
                                _this.$message.error(json.msg);
                            }
                    },function(err){
                        _this.$message.error('服务器错误')
                    }
                ) 
            }
            
        });
      },
      handleEdit(row) {
        this.editFormVisibe = true;
        this.editForm.id = row.id;
      },
      handleAddAction(row){
        this.addForm.user_id = row.id;
        this.addFormVisibe = true;
      },
      //添加用户   
      showAdduser(){
          this.addUserVisible=true;
      },
      // 新增动作指令
      addSubmitForm(formName){
        this.$refs[formName].validate(valid => {
          if (valid) {
            var _this = this;
            // var jsonWith = JSON.stringify(_this.addForm.moreNotifyObject);
            POST(
              urlApi+'action',
              {
                user_id:_this.addForm.user_id,
                name:_this.addForm.name,
                action:_this.addForm.action,
                content:_this.addForm.content,
                type:_this.addForm.type

              },
              function(json){
                console.log(json)
                if(json.code == 200){
                  _this.$message.success('创建成功');
                  _this.addFormVisibe = false;
                  _this.getTableData();
                } else {
                  _this.$message.error(json.message);
                }
              },
              function(err){
                _this.$message.error("服务器错误");
              }
            )
          }

        });
      },
      // 修改用户信息
      editSubmitForm(formName){
          var _this = this;
          var jsonArr = {};
          if($.trim(_this.editForm.password) != ''){
              jsonArr.password = $.trim(_this.editForm.password);
          }
          if($.trim(_this.editForm.name) != ''){
              jsonArr.name = _this.editForm.name.trim();
          }
          PUT(
              urlApi+'user/'+_this.editForm.id,
              jsonArr,
              function(json){
                  if(json.code == 200){
                  _this.$message.success('修改成功');
                  _this.editFormVisibe = false;
                  _this.getTableData();
                  } else {
                  _this.$message.error(json.message);
                  }
                  
              },function(err){
                  _this.$message.error("服务器错误");
              }
          )
        
      },
      // 获取用户列表
      getTableData(){
          var _this = this;
          GET(
              urlApi + 'user',
              {
                "page": _this.pagenumber,
                "num":10
              },function(json){
                  if(json.code == 200){
                      _this.total = json.total;
                      _this.tableData = [];
                     var data = json.data;
                     console.log(data);
                     if(data != null){
                        for(var i=0;i<data.length;i++){
                            var item = {};
                            item.No = i + 1;
                            item.id = data[i]['id'];
                            item.username = data[i]['username'];
                            item.type = data[i]['type'] == 'admin' ? '管理员':'企业用户';
                            item.name = data[i]['name'];
                            item.created_at = data[i]['created_at'];;
                            item.updated_at = data[i]['updated_at'];
                            _this.tableData.push(item);
                        } 
                     }
                      
                     
                  }
                //   console.log(json)
              },
              function(err){
                //   console.log(err);
                   _this.$message.error("服务器错误！");
              }
          )
      },
      // 数据初始化
      initData(){
        this.addForm.moreNotifyObject = []
      },
      // 新增携带参数/行
      addUser() {
            this.addForm.moreNotifyObject.push({
                field:'',
                name:'',
                max:'',
          })
      },
      // 删除携带参数/行
      deleteRules(item, index) {
        this.index = this.addForm.moreNotifyObject.indexOf(item)
        if (index !== -1) {
            this.addForm.moreNotifyObject.splice(index, 1)
        }
      },
      // 查看用户详情
      handleDetils(row){
        this.detailFormVisible = true;
        var _this = this;
         GET(
              urlApi + 'user/'+ row.id,
              {
               
              },function(json){
                  if(json.code == 200){
                     var data = json.data;
                     if(data != null){
                        _this.detailForm.id = data.id;
                        _this.detailForm.username = data.username;
                        _this.detailForm.type = data.type;
                        _this.detailForm.name = data.name;
                     }                  
                  }
              },
              function(err){
                _this.$message.error("服务器错误！");
              }
         )
      },
      // 表单重置
      resetForm(formName) {
        this.$refs[formName].resetFields();
      },
      // 分页
      handleCurrentChange(val) {
        // console.log(`当前页: ${val}`);
        this.pagenumber = val;
        this.getTableData();
    },
    }
  
}
</script>

<style>
.el-textarea__inner{
    min-height: 150px !important;
   
}
</style>
